import {
  ModalForm,
  ProForm,
  ProFormDateTimePicker,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Form, message } from 'antd';
import { useEffect } from 'react';

import { addTrippingRecord, updateTrippingRecord } from '../api';

interface EditDrawerProps {
  open: boolean;
  record: DORM_TRIPPING_RECORD.TrippingRecordModel | null;
  onFinish: () => void;
  onCancel: () => void;
}

/**
 * 宿舍跳闸记录编辑抽屉
 */
export default function TrippingRecordEditDrawer(props: EditDrawerProps) {
  const { open, record, onFinish, onCancel } = props;
  const [form] = Form.useForm();
  const isEdit = !!record;

  // 重置表单
  useEffect(() => {
    if (open) {
      if (record) {
        form.setFieldsValue(record);
      } else {
        form.resetFields();
        // 设置默认值
        form.setFieldsValue({
          isHandled: 0, // 默认未处理
        });
      }
    }
  }, [open, record, form]);

  // 添加跳闸记录请求
  const addRequest = useRequest(addTrippingRecord, {
    manual: true,
    onSuccess: () => {
      message.success('添加成功');
      onFinish();
    },
  });

  // 更新跳闸记录请求
  const updateRequest = useRequest(updateTrippingRecord, {
    manual: true,
    onSuccess: () => {
      message.success('更新成功');
      onFinish();
    },
  });

  // 提交表单
  const handleSubmit = async (values: any) => {
    if (!values.trippingPower) {
      values.trippingPower = 0;
    }

    // 验证：如果是已处理状态，跳闸功率必须大于等于1000瓦
    if (values.isHandled === 1 && (values.trippingPower === 0 || values.trippingPower < 1000)) {
      message.error('已处理的跳闸记录，跳闸功率必须大于等于1000瓦');
      return false;
    }

    if (isEdit && record) {
      // 更新跳闸记录
      await updateRequest.run({
        ...values,
        id: record.id,
      });
    } else {
      // 添加跳闸记录
      await addRequest.run(values);
    }
  };

  return (
    <ModalForm
      title={isEdit ? '编辑跳闸记录' : '新增跳闸记录'}
      form={form}
      open={open}
      onFinish={handleSubmit}
      onOpenChange={(visible) => {
        if (!visible) {
          onCancel();
        }
      }}
      submitter={{
        searchConfig: {
          submitText: isEdit ? '更新' : '提交',
        },
        resetButtonProps: {
          style: {
            display: 'none',
          },
        },
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="dormitoryNum"
          label="宿舍号"
          width="md"
          placeholder={'例：80118'}
          rules={[{ required: true, message: '请输入宿舍号' }]}
        />
        <ProFormText
          name="studentName"
          label="学生姓名"
          width="md"
          rules={[{ required: true, message: '请输入学生姓名' }]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormText
          name="className"
          label="班级名称"
          width="md"
          rules={[{ required: true, message: '请输入班级名称' }]}
        />
        <ProFormText
          name="counselor"
          label="辅导员姓名"
          width="md"
          rules={[{ required: true, message: '请输入辅导员姓名' }]}
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormDigit
          name="trippingPower"
          label="跳闸功率(瓦)"
          width="md"
          min={0}
          dependencies={['isHandled']}
          rules={[
            {
              validator: (_, value) => {
                const isHandled = form.getFieldValue('isHandled');
                if (isHandled === 1 && (value === 0 || value < 1000)) {
                  return Promise.reject('已处理的跳闸记录，跳闸功率必须大于等于1000瓦');
                }
                return Promise.resolve();
              },
            },
          ]}
        />
        <ProFormDateTimePicker
          name="trippingTime"
          label="跳闸时间"
          width="md"
          rules={[{ required: true, message: '请选择跳闸时间' }]}
        />
      </ProForm.Group>

      <ProFormSelect
        name="isHandled"
        label="处理状态"
        width="md"
        options={[
          { label: '未处理', value: 0 },
          { label: '已处理', value: 1 },
        ]}
        rules={[{ required: true, message: '请选择处理状态' }]}
      />
    </ModalForm>
  );
}
